import React from "react";
const Pay = () => {
    const back = () => {
        React.navigate(-1)
    }

    React.useEffect(()=>{
        getOrderData()
    },[])

    const busid = React.Business.id
    // 接收订单id
    const [useSearchParams] = React.Router.useSearchParams()
    const [orderid, setOrderid] = React.useState(useSearchParams.get("orderid"))
    // 获得订单数据
    let [order,setOrder] = React.useState({
        price:"0",
        name:"",
        code:"",
        paytype:"0",
        wxcode:"",
        zfbcode:"",
        id:0
    })
    const getOrderData = async () => {
        let result = await React.HTTP.post("/pay/pay",{orderid,busid})
        if(result.code == 1){
            const data = JSON.parse(result.data)
            order = data.data
            setOrder(order)
            // 开启定时器
            timer = setInterval(autocheck,1000)
        }else{
            React.error(result.msg,()=>{
                React.navigate(-1)
            })
            return false
        }
    }

    // 定时器
    let [sec,setSec] = React.useState(180)
    let timer:any = null
    const autocheck = async () => {
        if(sec <= 0){
            // 图片过期
            setOrder({...order,wxcode:"/assets/images/pay/qrcode_timeout.png",zfbcode:"/assets/images/pay/qrcode_timeout.png"})
            // 停止定时器
            clearInterval(timer)
        }
        sec = sec -1
        setSec(sec)

        if(sec%5 == 0){
            await query()
        }
    }

    // 检测是否支付
    const query = async () => {
        const result = await React.HTTP.post("/pay/query",{payid:order.id,busid})
        if(result.code == 1){
            if(result.data.status == "1"){
                // 停止定时器
                clearInterval(timer)
                React.success("支付成功",()=>{
                    React.navigate("/business/orderInfo?orderid="+orderid)
                })
            }
        }else{
            React.error(result.msg)
            return false
        }
    }


    return (<>
        <link rel="stylesheet" href="/assets/css/pay.css" />
         <React.UI.NavBar
            onBack={back}
            style={{ background: `rgb(55, 68, 134)`, color: '#fff' }}
        >支付</React.UI.NavBar>

        <h3 className="PayTitle">提示：付款金额要与显示的金额一致，否则后果自负</h3>
        <div className="PayAmount">
      <span>￥</span>
      <span>{order.price}元</span>
  </div>

  <div className="PayCode">
      <img src={order.paytype=="0"?order.wxcode:order.zfbcode} />
  </div>

  <div className="PayInfo">
      <div className="name">订单名称：{order.name}</div>
      <div className="code">订单号：{order.code}</div>
      <div className="box">
          <span className="tip">订单支付有效期</span>
          <span className="sec">{sec} 秒</span>
      </div>
  </div>
    </>)
}

export default Pay